<template>
  <el-drawer
    v-model="visible"
    title="新增商品"
    direction="rtl"
    size="560px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="productFormRef"
      :model="productForm"
      :rules="productRules"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品编码" prop="code">
            <el-input v-model="productForm.code" placeholder="请输入商品编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="电子产品" value="电子产品" />
              <el-option label="服装鞋帽" value="服装鞋帽" />
              <el-option label="家居用品" value="家居用品" />
              <el-option label="食品饮料" value="食品饮料" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-select v-model="productForm.unit" placeholder="请选择单位" style="width: 100%">
              <el-option label="个" value="个" />
              <el-option label="台" value="台" />
              <el-option label="件" value="件" />
              <el-option label="套" value="套" />
              <el-option label="盒" value="盒" />
              <el-option label="包" value="包" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="规格" prop="specification">
        <el-input v-model="productForm.specification" placeholder="请输入商品规格" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购价" prop="purchasePrice">
            <el-input-number 
              v-model="productForm.purchasePrice" 
              :min="0" 
              :precision="2"
              style="width: 100%"
              placeholder="请输入采购价"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售价" prop="salePrice">
            <el-input-number 
              v-model="productForm.salePrice" 
              :min="0" 
              :precision="2"
              style="width: 100%"
              placeholder="请输入销售价"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="库存" prop="stock">
        <el-input-number 
          v-model="productForm.stock" 
          :min="0"
          style="width: 200px"
          placeholder="请输入库存数量"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="productForm.status">
          <el-radio label="启用">启用</el-radio>
          <el-radio label="禁用">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品图片" prop="image">
        <el-upload
          class="image-uploader"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
          action="#"
        >
          <el-image
            v-if="productForm.image"
            :src="productForm.image"
            class="uploaded-image"
            fit="cover"
          />
          <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="productForm.description" 
          type="textarea" 
          :rows="3"
          placeholder="请输入商品描述" 
        />
      </el-form-item>

      <el-divider content-position="left">SKU配置</el-divider>

      <el-form-item label="启用SKU">
        <el-switch v-model="skuEnabled" active-text="启用" inactive-text="关闭" />
      </el-form-item>

      <div v-if="skuEnabled" class="sku-config">
        <div
          v-for="(attr, index) in skuAttributes"
          :key="index"
          class="attribute-config"
        >
          <div class="attr-header">
            <h4>属性 {{ index + 1 }}</h4>
            <el-button type="danger" size="small" text @click="handleRemoveAttribute(index)">
              删除
            </el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="属性名称">
                <el-input v-model="attr.name" placeholder="如：颜色、尺码" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="属性值">
                <el-tag
                  v-for="(value, vIndex) in attr.values"
                  :key="vIndex"
                  closable
                  @close="handleRemoveValue(index, vIndex)"
                  style="margin-right: 10px"
                >
                  {{ value }}
                </el-tag>
                <el-input
                  v-model="attr.newValue"
                  placeholder="输入后回车添加"
                  style="width: 200px"
                  @keyup.enter="handleAddValue(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-button type="primary" plain @click="handleAddAttribute">
          <el-icon><Plus /></el-icon>
          添加属性
        </el-button>

        <el-divider />

        <el-alert
          v-if="skuCombinationCount > 0"
          :title="`将生成 ${skuCombinationCount} 个SKU`"
          type="info"
          :closable="false"
          style="margin-bottom: 10px"
        />

        <div class="sku-actions" style="margin-bottom: 10px">
          <el-button type="primary" @click="generateSKUs">
            <el-icon><Plus /></el-icon>
            生成SKU
          </el-button>
        </div>

        <el-table v-if="generatedSKUs.length" :data="generatedSKUs" stripe style="margin-top: 10px">
          <el-table-column prop="skuCode" label="SKU编码" width="160" />
          <el-table-column label="规格组合" min-width="200">
            <template #default="{ row }">
              <el-tag
                v-for="(value, key) in row.specifications"
                :key="key"
                size="small"
                style="margin-right: 5px"
              >
                {{ key }}:{{ value }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template #default="{ row }">
              <el-input-number
                v-model="row.price"
                :min="0"
                :precision="2"
                size="small"
                style="width: 120px"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存" width="120">
            <template #default="{ row }">
              <el-input-number
                v-model="row.stock"
                :min="0"
                size="small"
                style="width: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <div class="drawer-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        确定
      </el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'submitted'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const submitLoading = ref(false)
const productFormRef = ref()

const productForm = reactive({
  code: '',
  name: '',
  category: '',
  specification: '',
  unit: '',
  purchasePrice: 0,
  salePrice: 0,
  stock: 0,
  status: '启用',
  image: '',
  description: ''
})

const productRules = {
  code: [
    { required: true, message: '请输入商品编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购价', trigger: 'blur' }
  ],
  salePrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' }
  ]
}

// SKU相关状态与方法
const skuEnabled = ref(false)
const skuAttributes = ref([{ name: '', values: [], newValue: '' }])
const generatedSKUs = ref([])

const skuCombinationCount = computed(() => {
  const validAttrs = skuAttributes.value.filter(attr => attr.name && attr.values.length > 0)
  if (validAttrs.length === 0) return 0
  return validAttrs.reduce((count, attr) => count * attr.values.length, 1)
})

const handleAddAttribute = () => {
  skuAttributes.value.push({ name: '', values: [], newValue: '' })
}

const handleRemoveAttribute = (index) => {
  skuAttributes.value.splice(index, 1)
}

const handleAddValue = (index) => {
  const attr = skuAttributes.value[index]
  if (attr.newValue && attr.newValue.trim()) {
    attr.values.push(attr.newValue.trim())
    attr.newValue = ''
  }
}

const handleRemoveValue = (attrIndex, valueIndex) => {
  skuAttributes.value[attrIndex].values.splice(valueIndex, 1)
}

const cartesianProduct = (arrays) => {
  return arrays.reduce((acc, array) => {
    return acc.flatMap(x => array.map(y => [...x, y]))
  }, [[]])
}

const generateSKUs = () => {
  const validAttrs = skuAttributes.value.filter(attr => attr.name && attr.values.length > 0)
  if (validAttrs.length === 0) {
    ElMessage.warning('请至少配置一个属性')
    return
  }
  if (!productForm.code) {
    ElMessage.warning('请先填写商品编码')
    return
  }

  const combinations = cartesianProduct(validAttrs.map(attr => 
    attr.values.map(value => ({ name: attr.name, value }))
  ))

  generatedSKUs.value = combinations.map((combo) => {
    const specs = {}
    let skuCode = `${productForm.code}-`

    combo.forEach((item, i) => {
      specs[item.name] = item.value
      skuCode += item.value.substring(0, 3).toUpperCase()
      if (i < combo.length - 1) skuCode += '-'
    })

    return {
      skuCode,
      specifications: specs,
      price: Number(productForm.salePrice) || 0,
      stock: 0
    }
  })
}

const handleImageSuccess = (response, file) => {
  productForm.image = URL.createObjectURL(file.raw)
  ElMessage.success('图片上传成功')
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const resetForm = () => {
  Object.assign(productForm, {
    code: '',
    name: '',
    category: '',
    specification: '',
    unit: '',
    purchasePrice: 0,
    salePrice: 0,
    stock: 0,
    status: '启用',
    image: '',
    description: ''
  })
  productFormRef.value?.clearValidate()
  // 重置SKU相关状态
  skuEnabled.value = false
  skuAttributes.value = [{ name: '', values: [], newValue: '' }]
  generatedSKUs.value = []
}

const handleSubmit = async () => {
  if (!productFormRef.value) return

  try {
    await productFormRef.value.validate()

    // 若启用SKU，需确保已生成SKU
    if (skuEnabled.value && generatedSKUs.value.length === 0) {
      ElMessage.warning('请先生成SKU')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    let totalStock = productForm.stock
    let skus = []
    let attrs = []

    if (skuEnabled.value) {
      attrs = skuAttributes.value
        .filter(attr => attr.name)
        .map(attr => ({ name: attr.name, values: attr.values.slice() }))

      skus = generatedSKUs.value.map(sku => ({
        skuCode: sku.skuCode,
        specifications: sku.specifications,
        price: Number(sku.price) || 0,
        stock: Number(sku.stock) || 0,
        status: true
      }))

      totalStock = skus.reduce((sum, s) => sum + Number(s.stock || 0), 0)
    }

    const newProduct = {
      ...productForm,
      stock: totalStock,
      skuEnabled: skuEnabled.value,
      skuAttributes: attrs,
      skus,
      skuCount: skus.length,
      id: Date.now(),
      createTime: new Date().toLocaleString()
    }

    emit('submitted', newProduct)
    visible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.attribute-config {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 12px;
}
.attr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.sku-config {
  padding: 10px 0;
}
</style>

<style scoped>
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 10px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.uploaded-image {
  width: 100px;
  height: 100px;
  display: block;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>